package com.utils;

import com.app.utils.JsonUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author feng
 * @date  2018-5-28
 *
 */
@SuppressWarnings("all")
public class HttpUtil {
	private static HashMap<String, String> headers = new HashMap<String, String>();
	public static String url = "";
	static {
		
	}

	public static void addHeader(String name, String value) {
		headers.put(name, value);
	}

	public static String post(String uri, Map<String, String> map) {
		return execute(uri, map, RestfulHttpClient.METHOD_POST);
	}

	public static String get(String uri, Map<String, String> map) {
		return execute(uri, map, RestfulHttpClient.METHOD_GET);
	}

	public static String put(String uri, Map<String, String> map) {
		return execute(uri, map, RestfulHttpClient.METHOD_PUT);
	}

	public static String delete(String uri, Map<String, String> map) {
		return execute(uri, map, RestfulHttpClient.METHOD_DELETE);
	}

	public static String patch(String uri, Map<String, String> map) {
		return executeHttpPatch(uri, JsonUtil.formatToStr(map));
	}
	
	public static String post(String uri, List<String> params) {
		try {
			URL methodUrl = new URL(url + uri);
			HttpRequestHandler hr = new HttpRequestHandler();
			String result = hr.postRequest(methodUrl, headers, params);
			System.out.println(result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String execute(String uri, Map map, String method) {
		try {
			RestfulHttpClient.HttpClient client = RestfulHttpClient.getClient(url + uri);
			// 设置请求
			if (RestfulHttpClient.METHOD_POST.equals(method)) {
				client.post();
			} else if (RestfulHttpClient.METHOD_GET.equals(method)) {
				client.get();
			} else if (RestfulHttpClient.METHOD_PATCH.equals(method)) {
				client.patch();
			} else if (RestfulHttpClient.METHOD_DELETE.equals(method)) {
				client.delete();
			} else if (RestfulHttpClient.METHOD_PUT.equals(method)) {
				client.put();
			} else {
				client.post();
			}
			// 添加header
			if (headers != null) {
				Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry<String, String> entry = it.next();
					client.addHeader(entry.getKey(), entry.getValue());
				}
			}
			// 添加参数 get请求 参数放url上，其他请求放body里面（raw方式）
			if (map != null) {
				if (RestfulHttpClient.METHOD_GET.equals(method)) {
					Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
					while (it.hasNext()) {
						Map.Entry<String, String> entry = it.next();
						client.addQueryParam(entry.getKey(), entry.getValue());
					}
				} else {
					client.body(map);
					/*Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
					while (it.hasNext()) {
						Map.Entry<String, String> entry = it.next();
						client.addPostParam(entry.getKey(), entry.getValue());
					}*/
				}
			}
			client.addHeader(
					"User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.5482.400 QQBrowser/9.7.13292.400");
            client.addHeader(
                    "User-Agent",
                    "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36");

            // 发起请求
			RestfulHttpClient.HttpResponse response = client.request();
			// 响应状态码
			System.out.println("响应状态码:"+response.getCode());
			// 最终发起请求的地址
			System.out.println("最终发起请求的地址:"+response.getRequestUrl());
			if (response.getCode() == 200) {
				// 请求成功
				// 响应内容
				System.out.println("响应内容:"+response.getContent());
			}
			String result = response.getContent();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String executeHttpPatch(String uri, String jsonParam) {

		if (!uri.startsWith("/")) {
			uri = "/" + uri;
		}
		String result = null;
		org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
		HttpPatch httpPatch = new HttpPatch(url + uri);
		httpPatch.setHeader("Content-type", "application/json");
		httpPatch.setHeader("Charset", "UTF-8");
		httpPatch.setHeader("Accept", "application/json");
		httpPatch.setHeader("Accept-Charset", "UTF-8");
		// 添加header
		if (headers != null) {
			Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> entry = it.next();
				httpPatch.setHeader(entry.getKey(), entry.getValue());
			}
		}
		try {
			if (jsonParam != null) {
				StringEntity entity = new StringEntity(jsonParam.toString(), HTTP.UTF_8);
				httpPatch.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPatch);
			result = inputStreamToString(response.getEntity().getContent());
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String inputStreamToString(InputStream is) {
		String line = "";
		StringBuilder total = new StringBuilder();
		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		try {
			// Read response until the end
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Return full string
		return total.toString();
	}

}
